package com.bmslz.monitor.base.config.excep;

import com.bmslz.monitor.base.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestControllerAdvice
@Slf4j
public class ExceptionAdvice {
    @ExceptionHandler(MyException.class)
    public Result<?> doExceptionMyException(MyException e) {
        String message = e.getMessage();
        Result<Object> result = Result.error(message);
        result.setCode(e.getCode());
        result.setSuccess(false);
        e.printStackTrace();
        return result;
    }


    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Result<?> doExceptionSQLIntegrityConstraintViolationException(SQLIntegrityConstraintViolationException e) {
        String message = e.getMessage();
        // 尝试提取重复的值和索引名称
        Pattern pattern = Pattern.compile("Duplicate entry '(.*?)' for key '(.*?)'");
        Matcher matcher = pattern.matcher(message);
        if (matcher.find()) {
            String duplicateValue = matcher.group(1);
            String indexName = matcher.group(2);
            message = String.format("值 '%s' 已存在，请使用其他值", duplicateValue);
        }
        Result<Object> result = Result.error(message);
        result.setCode(500);
        result.setSuccess(false);
        return result;
    }
}
